package upload

import (
	"errors"
	"image"
	"image/jpeg"
	"image/png"
	"log"
	"mime/multipart"
	"os"
	"path/filepath"

	"github.com/nfnt/resize"
)

// path 图片url
func CutImg(file *multipart.FileHeader, dst string) error {
	imgfile, err := file.Open()
	if err != nil {
		return err
	}

	defer imgfile.Close() // 关流
	if err = os.MkdirAll(filepath.Dir(dst), 0750); err != nil {
		return err
	}
	decodeBuf, layout, err := image.Decode(imgfile)
	b := decodeBuf.Bounds()
	width := float32(b.Max.X) * 0.6
	height := float32(b.Max.Y) * 0.6
	if err != nil {
		return err
	}
	set := resize.Resize(uint(width), uint(height), decodeBuf, resize.Lanczos3)
	//保存到新文件中
	newfile, err := os.Create(dst)
	if err != nil {
		log.Println("Create::", err)
		return err
	}
	switch layout {
	case "png":
		err = png.Encode(newfile, set)
	case "jpeg", "jpg":
		err = jpeg.Encode(newfile, set, &jpeg.Options{Quality: 80})
	default:
		return errors.New("该图片格式不支持压缩")
	}
	defer newfile.Close()
	if err != nil {
		log.Println("Encode::", err)
		return err
	}

	return nil
}
